﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.WizardAgent.Helpers
{
    /// <summary>
    /// Wizard接口的http请求类
    /// </summary>
    /// <remarks>
    /// 参考网址：C#中HttpClient使用注意：预热与长连接
    ///             http://www.cnblogs.com/dudu/p/csharp-httpclient-attention.html
    /// </remarks>
    public class WizardHttpClient
    {
        private static readonly log4net.ILog _Logger = log4net.LogManager.GetLogger(typeof(WizardHttpClient));
        private static readonly HttpClient _httpClient;
        static WizardHttpClient()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                UseProxy = false
            };
            _httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(20) };
            _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive"); // 长连接

            try
            {
                //帮HttpClient热身
                _httpClient.PostAsync(WizardConsts.OutboundUrl, new StringContent(WizardConsts.PingRQXML))
                    .Result.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                _Logger.Error("Wizard接口的http请求预热时报错！", ex);
            }
        }

        public async Task<string> PostXmlAsync(string requestXml)
        {
            if (string.IsNullOrEmpty(requestXml))
                throw new ArgumentNullException("requestXml");

            var response = await _httpClient.PostAsync(WizardConsts.OutboundUrl, new StringContent(requestXml));
            return await response.Content.ReadAsStringAsync();
        }

        public static string PostXml(string requestXml)
        {
            if (string.IsNullOrEmpty(requestXml))
                throw new ArgumentNullException("requestXml");

            var response = _httpClient.PostAsync(WizardConsts.OutboundUrl, new StringContent(requestXml)).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
}
